package com.ding.easycontroller.bean;

import com.ding.easycontroller.exception.ScriptRuntimeException;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashSet;
import java.util.Set;

@Component
public class ConsoleWork {


    @Autowired
    private ScriptEngine scriptEngine;

    private Set<Writer> writers = new HashSet<>();

    {
        //添加一个输出流
        writers.add(new OutputStreamWriter(System.out));
    }

    private void println(String s) {
        for (Writer writer : writers) {
            try {
                writer.write(s + "\n");
                writer.flush();
            } catch (IOException ignore) {
            }
        }

    }

    public void addWriter(Writer writer) {
        writers.add(writer);
    }

    public void removeWriter(Writer writer) {
        writers.remove(writer);
    }

    public void log(Object object) {

        if (object == null) {
            log("null");
            return;
        }

        if (object instanceof ScriptObjectMirror) {
            try {
                String r = (String) ((Invocable) scriptEngine).invokeFunction("__objToString", object);
                println(r);
            } catch (ScriptException e) {
                throw new ScriptRuntimeException(e);
            } catch (NoSuchMethodException ignore) {
            }
        } else {
            println(object.toString());
        }
    }

}
